<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="" prop="designFabricName">
        <!-- <el-input v-model="queryParams.designFabricName" placeholder="请输入面料名称" clearable
           /> -->
        <el-select
          v-model="queryParams.designFabricName"
          clearable
          filterable
          placeholder="主面料名称"
          @keyup.enter.native="handleQuery"
          allow-create
          default-first-option
        >
          <el-option
            v-for="(item, index) in mianliao"
            :key="index"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="procureWeavingPeriod">
        <el-input
          v-model="queryParams.procureWeavingPeriod"
          placeholder="请输入采购-织坯期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="procureStainPeriod">
        <el-input
          v-model="queryParams.procureStainPeriod"
          placeholder="请输入采购-染色期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="designFabricFunction">
        <el-input
          v-model="queryParams.designFabricFunction"
          placeholder="面料功能"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:cycle:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:cycle:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:cycle:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:cycle:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" plain icon="el-icon-upload" @click="daoru"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" @click="handleReport">同步检测报告</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="cycleList"
      @selection-change="handleSelectionChange"
      @row-dblclick="t"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="面料ID" align="center" prop="id" />
      <el-table-column
        label="面料名称"
        align="center"
        prop="designFabricName"
      />
      <el-table-column
        label="采购-织坯期"
        align="center"
        prop="procureWeavingPeriod"
      />
      <el-table-column
        label="采购-染色期"
        align="center"
        prop="procureStainPeriod"
      />
      <el-table-column
        label="面料功能"
        align="center"
        prop="designFabricFunction"
      >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="bottom" width="300">
            <!-- <span>{{ scope.row.designFabricFunction }}</span> -->
            <el-input
              v-model="scope.row.designFabricFunction"
              :min-height="192"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 24 }"
              :style="{ width: '100%' }"
              :disabled="true"
            />
            <div slot="reference">
              <span class="textname">
                {{ scope.row.designFabricFunction }}
              </span>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        width="110px"
        :label="'面料检测报告'"
        align="center"
        prop="fabricTestRepor"
      >
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="bottom" width="300">
            <!-- <span>{{ scope.row.customerProductTalking }}</span> -->
            <el-input
              v-model="scope.row.fabricTestRepor"
              :min-height="192"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 24 }"
              :style="{ width: '100%' }"
              :disabled="true"
            />
            <div slot="reference">
              <span class="textname">{{ scope.row.fabricTestRepor }} </span>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:cycle:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:cycle:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改面料属性-生产周期对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      v-if="open"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="面料名称" prop="designFabricName">
          <el-input
            v-model="form.designFabricName"
            placeholder="请输入面料名称"
          />
        </el-form-item>
        <el-form-item label="采购-织坯期" prop="procureWeavingPeriod">
          <el-input
            v-model="form.procureWeavingPeriod"
            placeholder="请输入采购-织坯期"
          />
        </el-form-item>
        <el-form-item label="采购-染色期" prop="procureStainPeriod">
          <el-input
            v-model="form.procureStainPeriod"
            placeholder="请输入采购-染色期"
          />
        </el-form-item>

        <el-form-item label="面料功能" prop="designFabricFunction">
          <!-- <el-input v-model="form.designFabricFunction" placeholder="面料功能" /> -->

          <!-- <el-select
            v-model="checked"
            placeholder="面料功能"
            clearable
            multiple
            @change="test"
          >
            <el-option
              v-for="dict in dict.type.sys_design_function"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select> @input="onFocus"-->
          <el-input
            type="textarea"
            v-model="form.designFabricFunction"
            placeholder="面料功能"
            :autosize="{ minRows: 4, maxRows: 12 }"
            :style="{ width: '100%' }"
            @input="changeMessage"
          />
          <el-autocomplete
            :trigger-on-focus="true"
            class="inline-input"
            :fetch-suggestions="queryOptions"
            placeholder="请输入"
            :autosize="{ minRows: 4, maxRows: 12 }"
            :style="{ width: '100%' }"
            :debounce="0"
            @select="clickSelect"
            v-model="xxxx"
          ></el-autocomplete>
        </el-form-item>
        <!-- popper-class="autocomplete" -->
        <!-- <el-form-item label=" ">
          
        </el-form-item> -->

        <el-form-item
          label="面料检测报告"
          prop="fabricTestRepor"
          label-width="100px"
        >
          <el-input
            v-model="form.fabricTestRepor"
            placeholder="面料检测报告"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 12 }"
            :style="{ width: '100%' }"
          />

          <!-- <el-upload :action="imgUpload.url" :headers="imgUpload.headers" :limit="limit"
    :on-exceed="handleExceed" :on-success="handlePictureSuccess"
    :before-upload="beforeAvatarUpload" :file-list="filefabricTestRepor"
    :on-change="changeFile2" ref="fabricTestRepor">
    <el-button size="small" type="primary">选择文件</el-button>


</el-upload> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改产品二级信息对话框 :on-change="handleChange"-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-upload
        :action="Upload.url"
        :headers="Upload.headers"
        :limit="limit"
        :on-exceed="handleExceed"
        :on-success="handlePictureSuccessPic"
        :before-upload="beforeAvatarUpload"
        :on-preview="handlePictureCardPreview"
        :file-list="fileLi"
        :on-change="changeFile1"
      >
        <el-button size="small" type="primary">导入文件</el-button>
        <!-- <i class="el-icon-plus"></i> -->
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
// import {
//   listKeyword,
//   getKeyword,
//   delKeyword,
//   addKeyword,
//   updateKeyword,
//   queryContentByKey,
// } from "@/api/data/keyword";
// import { listFabric, getInfoByName, selectFabricNameList } from "@/api/data/Fabric";
import {
  listFabric,
  getFabric,
  delFabric,
  addFabric,
  updateFabric,
  selectFabricNameList,
  synProDesignFabricByIds,
  queryContentByKey,
} from "@/api/data/Fabric";
import {
  listCycle,
  getCycle,
  delCycle,
  addCycle,
  updateCycle,
} from "@/api/data/cycle";
//--------导入token
import { getToken } from "@/utils/auth";
export default {
  name: "Cycle",
  dicts: ["sys_design_function"],
  data() {
    return {
      //文案辅助输入
      xxxx: "",
      allInfos: [],
      //面料名称
      mianliao: [],
      checked: [],
      // fileLi: [{ url: "" }],
      fileLi: [],
      file: "",
      dialogVisible: false,
      Upload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 图片上传的方法地址: /product/Fabric/importProduceDesignFabric
        url:
          process.env.VUE_APP_BASE_API +
          "/product/Fabric/importProduceDesignFabric",
      },
      // 图片数量限制
      limit: 2,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 面料属性-生产周期表格数据
      cycleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        designFabricName: null,
        procureWeavingPeriod: null,
        procureStainPeriod: null,
      },
      // 表单参数
      form: {
        // designFabricFunction: []
      },
      // 表单校验
      rules: {
        designFabricName: [
          { required: true, message: "面料名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getmianliao();
  },
  methods: {
    changeMessage() {
      this.$forceUpdate();
    },
    onFocus() {
      this.$forceUpdate;
    },
    //响应提示
    async queryOptions(queryString, cb) {
      console.log("queryString:", queryString);
      let options = [];
      //查询后端相关数据
      await queryContentByKey({ keyword: this.xxxx }).then((res) => {
        //赋值
        this.allInfos = res.data;
      });
      console.log(JSON.stringify(this.allInfos));
      // return
      //将结果中的gsmc提取出来
      // for (let i = 0; i < this.allInfos.length; i++) {
      //     //添加进options提示信息 注意 options的格式只能是 [...{"values":"xxx"}],如果不是这样的话，响应的result不能显示在页面上
      //     options.push({ "value": this.allInfos[i].storeCode });

      // }
      this.allInfos.forEach((item) => {
        // options.push({ value: item.copywritingContent, keyword: item.keyword });
        options.push({ value: item, keyword: item });
      });

      let changeQueryString = this.segmentation(queryString, [
        ",",
        "，",
        "。",
        "\n",
      ]);

      //过滤结果
      const results = changeQueryString
        ? options.filter(this.filterOptions(changeQueryString))
        : options;
      // 遍历数组，对每一项添加msg，其值为点击后应该呈现在输入框的值
      if (queryString != null) {
        results.map((item, index) => {
          results[index].msg =
            item.value !== changeQueryString
              ? queryString.slice(
                  0,
                  queryString.lastIndexOf(changeQueryString)
                ) + item.value
              : queryString;
          // results[index].msg = item.keyword !== changeQueryString ? queryString.slice(0, queryString.lastIndexOf(changeQueryString)) + item.keyword : queryString
        });
      }

      //回调结果
      cb(results);
    },
    // 返回一个过滤方法
    filterOptions(queryString) {
      return (state) => {
        // return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0 ||
        //     state.keyword.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        // );
        return state.value.toLowerCase().match(queryString.toLowerCase()) ||
          state.keyword.toLowerCase().match(queryString.toLowerCase())
          ? true
          : false;
      };
    },
    segmentation(queryString, arr) {
      if (queryString != null) {
        arr.map((item) => {
          queryString = queryString.slice(queryString.lastIndexOf(item) + 1);
        });
      }

      return queryString;
    },
    //点击方法
    clickSelect(msg) {
      console.log("msg", msg);
      if (this.form.designFabricFunction == null) {
        this.form.designFabricFunction = msg.msg;
      } else {
        // this.proTemplate.copywritingDesignPrinciple = this.proTemplate.copywritingDesignPrinciple + msg.msg
        this.form.designFabricFunction =
          this.form.designFabricFunction + msg.msg;
      }

      this.xxxx = "";
      // console.log(JSON.stringify(this.proTemplate + msg.msg));

      // if (msg.msg == undefined) {
      //     this.listQuery.storeCode = msg.value;
      // } else {
      //     this.listQuery.storeCode = msg.msg;
      // }
    },
    //同步面料检测报告
    handleReport() {
      if (this.ids.length <= 0) {
        this.$modal.msgError("请选择一条数据");
        return;
      }
      console.log(this.ids);
      synProDesignFabricByIds(this.ids.join(",")).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("同步面料检测报告成功");
        } else {
          this.$$modal.msgError("同步面料检测报告失败");
        }
      });
    },
    //面料名称
    getmianliao() {
      // this.loading = true;
      selectFabricNameList().then((response) => {
        console.log(JSON.stringify(response));
        this.mianliao = response;
        // console.log(JSON.stringify(this.FabricList));
        // this.total = response.total;
        // this.loading = false;
      });
    },
    //点击某一行
    t(row, column, cell, event) {
      // console.log(row, column, cell, event);
      // if (this.ids.length <= 0 || this.ids.length > 1) {
      //   this.$modal.msgError("请勾选一条数据");
      //   return;
      // }
      this.handleUpdate(row);
    },
    test(val) {
      console.log(JSON.stringify(val));
      // console.log(JSON.stringify(checked));
      this.form.designFabricFunction = this.checked.join();
      console.log(JSON.stringify(this.form.designFabricFunction));
    },
    //部门文件导入修改打开
    daoru() {
      this.dialogVisible = true;
    },
    /** 查询面料属性-生产周期列表 */
    getList() {
      this.loading = true;
      listFabric(this.queryParams).then((response) => {
        this.cycleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        designFabricName: null,
        procureWeavingPeriod: null,
        procureStainPeriod: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加面料属性-生产周期";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      // if (this.ids.length <= 0 || this.ids.length > 1) {
      //   this.$modal.msgError("请勾选一条数据");
      //   return;
      // }
      getFabric(id).then((response) => {
        this.form = response.data;
        console.log(JSON.stringify(response.data));
        // this.checked = response.data.designFabricFunction.split(',')
        // console.log(JSON.stringify(response.data.designFabricFunction.split(',')));
        this.checked = response.data.designFabricFunction
          ? response.data.designFabricFunction.split(",")
          : [];
        this.open = true;
        this.title = "修改面料属性-生产周期";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateFabric(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              synProDesignFabricByIds(this.form.id.toString()).then(
                (response) => {
                  if (response.code == 200) {
                    this.$modal.msgSuccess("同步面料检测报告成功");
                  } else {
                    this.$$modal.msgError("同步面料检测报告失败");
                  }
                }
              );
              this.open = false;
              this.getList();
            });
          } else {
            addFabric(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除面料属性-生产周期编号为"' + ids + '"的数据项？')
        .then(function () {
          return delFabric(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/Fabric/produceExport",
        {
          ...this.queryParams,
        },
        `cycle_${new Date().getTime()}.xlsx`
      );
    },
    //图片预览
    handlePictureCardPreview(file) {},
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 5;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isLt2M;
    },
    //文件导入成功回传

    handlePictureSuccessPic(res, file) {
      console.log(JSON.stringify(res));
      //设置图片访问路径 （url 后台传过来的的上传地址）
      // this.picUrl = file.response.url;
      // const url = file.response.fileName;
      this.file = file.response.url;
      console.log(JSON.stringify(this.file));
      if (res.code == 200) {
        this.$modal.msgSuccess("导入成功");
        this.dialogVisible = false;
        // this.$modal.msgError(res.msg);
        this.getList();
      } else {
        this.$modal.msgError(res.msg);
        this.dialogVisible = true;
        // this.$message.msgError('该颜色未在字典定义')
        return;
      }
    },
    // //图片上传成功后的回调
    // handlePictureSuccess(res, file) {
    //     //设置图片访问路径 （url 后台传过来的的上传地址）
    //     this.imageUrl = file.response.url;
    //     // const url = file.response.fileName;
    //     this.logoUrl = file.response.fileName;
    //     // console.log(JSON.stringify(url));
    // },

    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传链接文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传文件让第二次覆盖第一的文件
    changeFile1(file, fileList) {
      if (fileList.length > 1) {
        this.fileLi = fileList.slice(-1);

        // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
      }
      // this.fileSpecial = fileList;
    },
  },
};
</script>
<style lang="scss" scoped>
span.textname {
  display: -webkit-box;

  text-overflow: ellipsis;
  overflow: hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  white-space: pre-wrap;
}

.el-dialog-div {
  height: 80vh;
  overflow-x: hidden;
}

.el-input.is-disabled ::v-deep .el-input__inner {
  color: #606266;
  background-color: white;
  border: none;
}

.el-textarea.is-disabled ::v-deep .el-textarea__inner {
  color: #606266;
  background-color: white;
  border: none;
  width: 500px;
  resize: none;
  cursor: pointer;
}
</style>
